<?php
/**
*+-------sina微博用户接入控制器--------+
*+-------------------------------------------------+
*-------对于sina微博用户接入的控制处理
*+-------------------------------------------------+
*+-@author susy.liang <liangling@ilongyuan.com.cn>-+
*+-------------------------------------------------+
*/
namespace Auth\Event;

class SinaEvent extends PublicEvent {
	/**
	*成员变量的初始化
	*/
	protected function _initialize(){

		$this->params 	= 	C('thirdParty.sina');
		$this->appId 	= 	$this->params['appId'];
		$this->appKey 	= 	$this->params['appKey'];
	}

	/**
	*回调
	*/
	 public function callBack($param=array()){
	 	if($param['state'] && $param['code']){//code的回调
   			$state = session('state');
   			if($state != I('state')){
   				echo 'state参数不合法';
   				exit();
   			}
   			
   			$this->getToken($param['code'], U('Auth/callBack', array('channel'=>'sina')));

   		}elseif($param['access_token']){//token的回调
   			$token = I('access_token');
   			$openid = I('uid');
   			if(!$openid){
   				echo '获取用户标识失败';
   				exit();
   			}
           //$user = array('openid'=>$openid);
   			//TODO:add user
   			exit();
   		}
	 }


	/**
	*请求授权 authorize code
	*@param string $redirectUrl 回调的地址
	*@return boolean
	*/
	public function getCode($redirectUrl=''){
		if(empty($redirectUrl))
			return false;
		$redirectUrl = urlencode($redirectUrl);

		$state = md5(uniqid(time(), true));
		session('state', $state);

		$requestParam = array(
						'client_id'=>$this->appId,
						'redirect_uri'=>$redirectUrl,
						'state'=>$state,
			);
		$this->doHttp($this->params['codeApi'], $requestParam);

		return true;
	}

	/**
	*请求授权 token
	*/
	/**
	*sina请求token时会同时返回用户身份标识uid
	*{"access_token": "ACCESS_TOKEN","expires_in": 1234,"remind_in":"798114","uid":"12341234" }
	*/
	public function getToken($authCode='', $redirectUrl){
		if(empty($authCode) || empty($redirectUrl))
			return false;

		$requestParam = array(
						'client_id'=>$this->appId,
						'client_secret'=>$this->appKey,
						'grant_type'=>'authorization_code',
						'code'=>$authCode,
						'redirect_uri'=>$redirectUrl,
			);
		$this->doHttp($this->params['tokenApi'], $requestParam, false, 'post');
		return true;
	}

}